package com.example.springboot.mqtt.util;

import com.example.springboot.mqtt.config.MqttConfig;
import com.example.springboot.mqtt.listener.MqttListener;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class MqttUtil {

    @Autowired
    MqttConfig mqttConfig;
    private MqttClient client;

    /**
     * 初始化
     * @return
     */
    @PostConstruct
    private MqttClient initPublish(){
        if(client == null){
            try {
                client = new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId(), new MemoryPersistence());
                MqttConnectOptions options = new MqttConnectOptions();
                options.setUserName(mqttConfig.getUsername());
                options.setPassword(mqttConfig.getPassword().toCharArray());
                options.setCleanSession(false);
                options.setConnectionTimeout(60);
                options.setKeepAliveInterval(60);
                client.connect(options);
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }
        return client;
    }

    /**
     * 发布消息
     * @param topic
     * @param content
     */
    public void publish(String topic, String content) {
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(1); //0: 一次性发送，1: 并发发送，2: 只能接收到一次
        message.setRetained(false); //是否保留消息
        try {
            client.publish(topic, message);
        }catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 订阅消息
     * @param topic
     */
    public void subscribe(String topic) {
        try {
            client.subscribe(topic, new MqttListener());
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消订阅
     * @param topic
     */
    public void unsubscribe(String topic) {
        try {
            client.unsubscribe(topic);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
}
